package com.example.nna.parserhtml;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;

import com.example.nna.util.UserInfo;

public class parser {
	String m_url;
	Document doc;
	UserInfo mUser;
	int mTimeout = 60000;
	public parser(String url){
		m_url = url;
		mUser = new UserInfo();
	}
	public String getUrl(){
		return m_url;
	}
	public void setUrl(String url){
		m_url = url;
	}
	public Document login(UserInfo mUser){
		this.mUser = mUser;
    	try {
			Response res = Jsoup.connect("http://vozforums.com/login.php?do=login")
					  .timeout(60000)
					  .data("do","login")
					  .data("vb_login_username",mUser.User())
					  .data("cookieuser", "1")
					  .data("vb_login_password",mUser.Pass())
					  .data("s", " ")
					  .data("securitytoken", mUser.Token())
					  .data("vb_login_md5password", mUser.md5Pass())
					  .data("vb_login_md5password_utf", mUser.md5Pass())
					  .method(Method.POST)
				      .execute();
			
			if(res.cookie("vfuserid") != null){
				mUser.cookies(res.cookies());
				mUser.setLogin(true); 
				return getDoc();
			}else 
				return null;	
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	public Document Logout(){
    	String urlLogout=null;
    	urlLogout = "http://vozforums.com/login.php?do=logout&"+
    			"logouthash=" + mUser.Token();
    	try {
    		Response  res = Jsoup.connect(urlLogout)
						.timeout(60000)
						.method(Method.POST)
						.execute();
			mUser.cookies(res.cookies());
			mUser.setLogin(false); 
			return getDoc();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
    }
    public Document getDoc(){
		try {
			if(mUser.cookies() == null){
				Connection con1 = Jsoup.connect(m_url);
				doc = con1.get();
			}else{
				doc = Jsoup.connect(m_url)
						.timeout(60000)
						.cookies(mUser.cookies())
						.get();
			}
	
			if(doc.select("td[class*=tcat]").first().text().equals("vBulletin Message")){
				return null;
			}else{
				return doc;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
}
